import React, { Component } from 'react';
import { Chart, Interval, Axis, registerShape } from 'bizcharts';
import { connect } from 'umi'
import { Empty } from 'antd'
import { isValueEmpty, formatterUnitOfData, isDecimal } from '@/utils/utils'
import styles from '../index.less'

export default class Histogram extends Component {
  constructor() {
    super()
  }

  render() {
    const { dataRow = [], staticts, axisName = 'time_value', valueName, minNumber = 0, isToFixed = true } = this.props
    const scale = {
      [valueName]: {
        min: minNumber,
        formatter: (val) => {
          const { value, unit } = formatterUnitOfData(staticts, val, isToFixed)
          if (value) {
            return value + unit.slice(0, -1);
          }
          return 0
        }
      }
    }

    const dataRowNumber = list => {
      list.forEach(item => {
        item[valueName] = parseFloat(item[valueName])
      })
      return list
    }

    const positionStr = `${axisName}*${valueName}`
    return (
      <>
        {isValueEmpty(valueName, dataRow) ?
          <Empty image={Empty.PRESENTED_IMAGE_SIMPLE} /> :
          <Chart autoFit data={dataRowNumber(dataRow)} scale={scale} appendPadding={[18, 0, 0, 0]}>
            <Interval position={positionStr}
              label={[valueName, (xValue) => {
                if (!xValue) return ''
                const isVeryBig = xValue > 100000
                let content = null
                if (isVeryBig) {
                  const { value, unit } = formatterUnitOfData(staticts, xValue)
                  content = value + unit.slice(0, -1)
                } else {
                  content = isDecimal(xValue) ? xValue.toFixed(2) : xValue
                }
                return {
                  content: content,
                  style: {
                    fill: '#b1b1b1',
                    fontSize: 12
                  },
                  layout: {
                    type: 'fixed-overlap',
                  }
                };
              }
              ]}
              color="l (270) 0:rgba(0,77,167,1) 1:rgba(0,244,255,1)"
              // color="#5fbbea"
              tooltip={[positionStr, (x, y) => {
                const { value, unit } = formatterUnitOfData(staticts, y)
                return {
                  name: staticts,
                  value: value + unit,
                };
              }]}
            />
            <Axis
              name={axisName}
              label={{ autoRotate: false }}
            />
            <Axis
              name={valueName}
              label={{ autoRotate: false }}
              grid={false}
            />
          </Chart>
        }
      </>
    )
  }
}
